﻿using MQTTnet;
using MQTTnet.Protocol;
using System.Buffers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MQTT.Client.Tuling
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private IMqttClient mqttClient;

        public MainWindow()
        {
            InitializeComponent();
            InitMqtt();
        }

        private async Task InitMqtt()
        {
            try
            {
                MqttClientFactory mqttFactory = new MqttClientFactory();
                mqttClient = mqttFactory.CreateMqttClient();
                MqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder()
                    .WithTcpServer("127.0.0.1", 1883)
                    .WithClientId("Client567")
                    .WithCleanSession(false)
                    .Build();
                MqttClientConnectResult connectResult = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
                MessageBox.Show($"Client567,{connectResult.ResultCode.ToString()}");
            }
            catch (Exception e)
            {
                MessageBox.Show($"Client567{e.Message}");
            }
        }

        /// <summary>
        /// 消息发布
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string topic = TbTopic.Text;
            string payload = $"{TbMessage.Text}-{DateTime.Now}";
            MqttApplicationMessage messageApplication = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(payload)
                .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce)
                .WithRetainFlag(false)
                .Build();

            await mqttClient.PublishAsync(messageApplication, CancellationToken.None);
        }

        /// <summary>
        /// 订阅消息并展示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                // 接收订阅主题的消息
                mqttClient.ApplicationMessageReceivedAsync += (e) =>
                {

                    ReadOnlySequence<byte> msgArray = e.ApplicationMessage.Payload;
                    var msg = Encoding.UTF8.GetString(msgArray);

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        TbShowMessage.Text += msg + "\r\n";
                    });

                    return Task.CompletedTask;
                };

                // 订阅主题
                await mqttClient.SubscribeAsync(new MqttClientSubscribeOptionsBuilder()
                    .WithTopicFilter(TbTopic.Text)
                    .Build());

                MessageBox.Show($"订阅主题:{TbTopic.Text}成功！");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
    }
}